﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebHoiChoMuaBan.Models;

namespace WebHoiChoMuaBan.Controllers.Helpers
{
    public class PhotoAlbumHelper : HelperBase
    {
        public PhotoAlbumHelper(): base()
        {

        }

        public struct FetchAlbumResult
        {
            public List<PhotoAlbum> albums;
            public int totalPages;
        }

        public List<PhotoAlbum> LoadAllAlbumsByUserId(int uid)
        {
            var news = (from n in this.dataContext.PhotoAlbums
                        where n.MemId == uid
                        orderby n.AlbumId descending
                        select n);
            return news.ToList();
        }

        public PhotoAlbum GetAlbumById(int albumId)
        {
            return this.dataContext.PhotoAlbums.SingleOrDefault(n => n.AlbumId == albumId);
        }

        private List<PhotoAlbum> CreateListAlbum(int page, int rowPerPage, IEnumerable<PhotoAlbum> album)
        {
            List<PhotoAlbum> pagedAlbum = album.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();

            int totalPages = (int)Math.Ceiling((double)album.Count() / rowPerPage);

            List<PhotoAlbum> lstAlbum = new List<PhotoAlbum>(totalPages);
            foreach (var item in pagedAlbum)
            {
                lstAlbum.Add(item);
            }
            return lstAlbum;
        }

        private FetchAlbumResult CreateFetchAlbum(int page, int rowPerPage, IEnumerable<PhotoAlbum> album)
        {
            List<PhotoAlbum> pagedAlbum = album.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();

            int totalPages = (int)Math.Ceiling((double)album.Count() / rowPerPage);

            List<PhotoAlbum> lstAlbum = new List<PhotoAlbum>(totalPages);
            foreach (var item in pagedAlbum)
            {
                lstAlbum.Add(item);
            }
            FetchAlbumResult result;
            result.totalPages = totalPages;
            result.albums = lstAlbum;
            return result;
        }

        public FetchAlbumResult getAllAlbum(int pageNum, int itemPerPage)
        {
            IEnumerable<PhotoAlbum> album = null;
            album = from n in this.dataContext.PhotoAlbums
                    orderby n.AlbumId descending
                    select n;
            return CreateFetchAlbum(pageNum, itemPerPage, album);
        }
        //
        // Insert/Delete Methods

        public void Add(PhotoAlbum album)
        {
            this.dataContext.PhotoAlbums.InsertOnSubmit(album);
        }

        //Delete Methods
        public void Delete(PhotoAlbum album)
        {
            this.dataContext.PhotoAlbums.DeleteOnSubmit(album);
        }

        public void Save()
        {
            this.dataContext.SubmitChanges();
        }
    }
}